// 云函数入口文件
const cloud = require('wx-server-sdk')
const {
    createReport
} = require('docx-templates')
const stringRandom = require('string-random')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
    const word = cloud.downloadFile({
        fileID: 'cloud://cloud1-8gfqhrbc74e68b7c.636c-cloud1-8gfqhrbc74e68b7c-1313218730/zqtys/知情同意书-新冠.docx'
    })
    const template = (await word).fileContent
    const time = new Date();
    let imageurl = event.image
    let imageurl2 = event.image2
    const image = await cloud.downloadFile({
        fileID:imageurl
    })
    const image2 = await cloud.downloadFile({
        fileID:imageurl2
    })
    const imagedata=(await image).fileContent
    const imagedata2=(await image2).fileContent

    const buffer = await createReport({
            template,
            data: {
                specimen:event.specimen,
                year: time.getFullYear(),
                month: time.getMonth() + 1,
                day: time.getDate(), // 这里的key值和你在word模板里面写的要一致，可以有多个
            },
            additionalJsContext: {
            getMapPicture: async () => {
                const res = await imagedata
                return {
                    width: 5,
                    height: 1.58,
                    data: res,
                    extension: '.png'
                };
        },
        getMapPicture2: async () => {
            const res = await imagedata2
            return {
                width: 5,
                height: 1.58,
                data: res,
                extension: '.png'
            };
    },
    },
        cmdDelimiter: ['{', '}'] // 分隔符
    });
const name=event.name
const random=stringRandom(6)
const randfilename=name+'_知情同意书_'+random
const preDir = time.getFullYear() + '年' +(time.getMonth() + 1)+'月' + time.getDate() +'日'
const cloudPath = `知情同意书word/${preDir}/${randfilename}.docx` //文件

return await cloud.uploadFile({
    cloudPath,
    fileContent: Buffer.from(buffer, 'hex')
})
}